﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace N2.Collections
{
	public class ChildrenListWrapper<TItem>: IList<TItem>
		where TItem: ContentItem
	{
		//wtf? it won't be of any use for IList<T>
		public TItem Create()
		{
			return Context.Definitions.CreateInstance<TItem>(this.m_owner);
		}

		#region Fields

		readonly ContentItem m_owner;
		
		#endregion Fields

		#region Constructors

		internal ChildrenListWrapper(ContentItem owner)
		{
			this.m_owner = owner;
		}

		#endregion Constructors

		#region IList<TItem> Members

		public int IndexOf(TItem item)
		{
			return this.m_owner.Children
				.OfType<TItem>()
				.TakeWhile(_child => _child != item)
				.Count() + 1;
		}

		public void Insert(int index, TItem item)
		{
			//TODO
			Utility.Insert(item, this.m_owner, index);
		}

		public void RemoveAt(int index)
		{
			//TODO
			var _item = this[index];

			if (null != _item) {
				this.Remove(_item);
			}
		}

		public TItem this[int index] {
			get { return (TItem)this.m_owner.Children[index]; }
			set {
				this.RemoveAt(index);
				this.Insert(index, value);
			}
		}

		#endregion

		#region ICollection<TItem> Members

		public void Add(TItem item)
		{
			item.AddTo(this.m_owner);
		}

		public void Clear()
		{//TODO
		}

		public bool Contains(TItem item)
		{
			return this.m_owner.Children.Contains(item);
		}

		public void CopyTo(TItem[] array, int arrayIndex)
		{
			this.m_owner.Children.CopyTo(array, arrayIndex);
		}

		public int Count { get { return this.m_owner.Children.OfType<TItem>().Count(); } }

		public bool IsReadOnly { get { return false; } }

		public bool Remove(TItem item)
		{
			return item.Parent.Children.Remove(item);
		}

		#endregion

		#region IEnumerable<TItem> Members

		public IEnumerator<TItem> GetEnumerator()
		{
			return this.m_owner.Children.OfType<TItem>().GetEnumerator();
		}

		#endregion

		#region IEnumerable Members

		IEnumerator IEnumerable.GetEnumerator()
		{
			return this.GetEnumerator();
		}

		#endregion
	}
}
